<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);
$deposit_id = intval($input['deposit_id'] ?? 0);

try {
    // 验证充值记录是否存在且属于当前用户
    $stmt = $pdo->prepare("
        SELECT id, status, amount 
        FROM deposit_records 
        WHERE id = ? AND user_id = ? AND status = 'pending'
    ");
    $stmt->execute([$deposit_id, $user_id]);
    $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$deposit) {
        throw new Exception('充值记录不存在或已处理');
    }
    
    // 更新状态为已取消
    $stmt = $pdo->prepare("
        UPDATE deposit_records 
        SET status = 'cancelled', processed_at = NOW() 
        WHERE id = ? AND user_id = ?
    ");
    $stmt->execute([$deposit_id, $user_id]);
    
    error_log("用户 {$user_id} 取消充值订单 {$deposit_id}，金额: ¥{$deposit['amount']}");
    
    echo json_encode([
        'success' => true,
        'message' => '充值订单已取消'
    ]);
    
} catch (Exception $e) {
    error_log("取消充值失败: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
